- Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path19. Remove Nth Node From End of List.c
59 lines (42 loc) · 1.07 KB
/
19. Remove Nth Node From End of List.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
19. Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
structListNode*removeNthFromEnd(structListNode*head, intn) {
structListNode*a, *b, *p=NULL;
a=b=head;
while (n-->0) { // b moves n steps first
b=b->next;
}
while (b) { // a, b move together, keeps a gap of n steps
p=a;
a=a->next;
b=b->next;
}
if (a==head) { // a is the one to be removed
head=a->next;
} else {
p->next=a->next;
}
free(a);
returnhead;
}
/*
Difficulty:Medium
Total Accepted:188.5K
Total Submissions:563.1K
Related Topics Linked List Two Pointers
*/